package com.elitel.common.utils.redissonLock;

import com.elitel.common.utils.SpringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;

/**
 * Redisson分布式锁工具类
 *
 * @author mulis
 */
public class RedissonLockUtil {

    private static final Redisson REDISSON;
    private static final String LOCK_ = "redisson:lock:";
    
    static {
        RedissonManager redissonManager = SpringUtils.getBean(RedissonManager.class);
        REDISSON = redissonManager.getRedisson();
    }


    /**
     * 使用demo
     */
    public void demo() {
        try {
            if (RedissonLockUtil.lock("test")) {
                //处理业务

            }
        } finally {
            RedissonLockUtil.unlock("test");
        }
    }

    /**
     * 加锁
     *
     * @param lockName 加锁对象
     * @return
     */
    public static boolean lock(String lockName) {
        String key = LOCK_ + lockName;
        //获取锁对象
        RLock rLock = REDISSON.getLock(key);
        //加锁，并设置锁超时时间 30秒
        rLock.lock(30, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 解锁
     *
     * @param lockName 解锁对象
     */
    public static void unlock(String lockName) {
        String key = LOCK_ + lockName;
        //获取锁对象
        RLock rLock = REDISSON.getLock(key);
        //解锁
        rLock.unlock();
    }

}
